<template>
  <div>
    <el-form ref="form" :model="form" size="mini" label-width="150px" :rules="rules" style="margin-top:20px;" label-position="left">
      <el-form-item label="供应商名称：">
        <el-col :span="5">
          <span>{{form.supplierName}}</span>
        </el-col>
      </el-form-item>
      <el-form-item label="采购价格协议名称：" prop="agreementName">
        <el-col :span="5">
          <el-input v-model="form.agreementName" maxlength="50"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="协议起止时间：" prop="dateRange">
        <el-date-picker v-model="form.dateRange" type="daterange" format="yyyy年 MM 月 dd 日" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="协议开始日期" end-placeholder="协议结束日期"> </el-date-picker>
      </el-form-item>
    </el-form>

    <div class="tableMain">
      <el-form :model="form" size="mini" style="width:90%;">
        <el-form-item>
          <el-button type="primary" size="mini" @click="_handleAddGoods()" style="margin-top:10px;float:right;">选择商品</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="tableData">
        <el-table-column type="index" label="序号" align="center"></el-table-column>
        <el-table-column prop="goodsName" label="商品名称" align="center"></el-table-column>
        <el-table-column prop="goodsSpec" label="规格型号" align="center">
          <template slot-scope="scope">
            <div v-for="(item,index) in scope.row.goodsSpec" :key="index">
              <span v-if="item!=null">{{item.paramName}} :</span>
              <span v-if="item!=null"> {{item.paramValue}} </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="purchaseUnit" label="采供单位" align="center"></el-table-column>
        <el-table-column prop="goodsPrice" label="单价" align="center">
          <template slot-scope="scope">
            <sd-input :val.sync="scope.row.goodsPrice"></sd-input>
          </template>
        </el-table-column>
        <el-table-column prop="isFreight" label="含运费" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.isFreight" active-color="#13ce66" inactive-color="#ff4949" active-value="1" inactive-value="0"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="freight" align="center" label="运费">
          <template slot-scope="scope">
            <sd-input :val.sync="scope.row.freight" v-show="scope.row.isFreight == '0'"></sd-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="_handleDelete(scope.$index)" type="text">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-form :model="form" size="mini" style="width:90%;margin-top:20px;">
        <el-form-item>
          <el-button type="primary" @click="onSubmit('form')" style="float:right;">确认</el-button>
          <el-button @click="goBack()" style="float:right;margin-right:20px;">取消</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 商品选择弹出框 -->
    <el-dialog title="商品选择" :visible.sync="goodsClass.dialog" :closeOnClickModal='false' :closeOnPressEscape='false'>
      <el-form size="mini">
        <el-form-item label="" label-width="0">
          <el-input v-model="selectData.keyWord" placeholder="输入商品名称/货号/条码搜索" style="width:200px;">
            <i slot="suffix" class="el-input__icon el-icon-search" @click="goodsClass.handleSearch(_findGoodsShopPage, goodsClass.pageData)"></i>
          </el-input>
        </el-form-item>
      </el-form>
      
      <el-table :data="goodsClass.tableData" ref="multipleTablegood" tooltip-effect="dark" @selection-change="goodsClass.handleMultipleSelect" :row-key="getRowKeys">
        <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
        <el-table-column type="index" width="50" label="序号" align="center"></el-table-column>
        <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
        <el-table-column prop="barCode" label="商品条码" align="center"></el-table-column>
        <el-table-column prop="name" label="商品名称" align="center"></el-table-column>
        <el-table-column prop="parameter" label="规格型号" align="center">
          <template slot-scope="scope">
            <div v-for="(item,index) in scope.row.parameter" :key="index">
              <span v-if="item!=null">{{item.paramName}} :</span>
              <span v-if="item!=null"> {{item.paramValue}} </span>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <page-unit :pageData="goodsClass.pageData" :func="_findGoodsShopPage"></page-unit>

      <el-form label-width="0" size="mini">
        <el-form-item>
          <el-button type="primary" @click="handleSelectGoods()" style="float:right;">确认</el-button>
          <el-button @click="goodsClass.dialog=false" style="float:right;margin-right:20px;">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";
import pageUnit from "components/Page";
import sdInput from "@/components/SdInput";
import u from "@/util";
import { TableHandle } from "@/util/class";
import { saveOrderPriceAgreement, findGoodsShopPage } from "@/api";

export default {
  computed: mapState(["sub", "merchantId", "userName"]),
  components: { pageUnit, sdInput },

  data () {
    return {
      getRowKeys(row) {
        return row.id; // 获取row的key值
      },
      form: {
        creater: '',  // 创建人
        supplierId: '',  // 供应商ID
        supplierName: '',  // 供应商名称
        customerId: '',  // 企业客户ID
        customerName: '',  // 企业客户名称
        agreementType: 0,  // 协议类型 0-自建 1-同步
        startDate: '',  // 开始时间
        endDate: '',  // 结束时间
        dateRange: '',
        agreementName: '',  // 协议名称
      },
      tableData: [],  // 价格协议的商品列表
      goodsClass: new TableHandle(), // 来源单商品数组对象
      selectData: {
        keyWord: ''
      },
      rules: {
        agreementName: [{ required: true, message: '请输入采购价格协议名称', trigger: 'blur' }],
        dateRange: [{ required: true, message: '请选择日期', trigger: 'change' }],
      }
    }
  },

  created () {
    this.form.supplierId = u.getQuery().supplierId
    this.form.supplierName = u.getQuery().supplierName
  },

  methods: {

    onSubmit (formName) {
      for(let i = 0; i < this.tableData.length; i++) {
        if(Number(this.tableData[i].isFreight) === 1) {
          this.tableData[i].freight = 0
        } else {
          if(this.tableData[i].freight == '' || this.tableData[i].freight == 0 || this.tableData[i].freight == undefined) {
            this.$message.error('输入运费不能为0或空！')
            return false
          }
        }
        if(this.tableData[i].goodsPrice == '' || this.tableData[i].goodsPrice == undefined) {
          this.$message.error('输入价格不能为空！')
          return false
        }
      }
      this.form.startDate = this.form.dateRange[0]
      this.form.endDate = this.form.dateRange[1]
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this._saveOrderPriceAgreement()
        } else {
          return false;
        }
      });
    },

    // 新增价格协议
    _saveOrderPriceAgreement () {
      saveOrderPriceAgreement({
        creater: this.merchantId,
        supplierId: this.form.supplierId,
        supplierName: this.form.supplierName,
        customerId: this.merchantId,
        customerName: this.userName,
        startDate: this.form.startDate,
        endDate: this.form.endDate,
        agreementName: this.form.agreementName,
        list: JSON.stringify(this.tableData)
      }).then(res => {
        if (res.code == 200) {
          history.back()
        }
      })
    },

    // 查询商品列表（用于添加价格协议）
    _findGoodsShopPage (pageSize, pageNum) {
      this.form.startDate = this.form.dateRange[0]
      this.form.endDate = this.form.dateRange[1]
      findGoodsShopPage({
        supplierId: this.form.supplierId,
        customerId: this.merchantId,
        startDate: this.form.startDate,
        endDate: this.form.endDate,
        searchInfo: this.selectData.keyWord,
        pageNo: pageNum,
        pageSize: pageSize,
        shopId: this.merchantId
      }).then(res => {
        this.goodsClass.tableData = res.data.list
        this.goodsClass.tableData.forEach(i => {
          i.goodsId = i.id,
          i.goodsSpec = i.parameter
        })
        this.goodsClass.pageData.totalItems = res.data.total
      })
    },

    // 点击选择商品按钮
    _handleAddGoods () {
      if (this.form.dateRange == '' || this.form.dateRange == undefined) {
        this.$message.error('请先选择协议时间')
        return
      } else {
        this._findGoodsShopPage(this.goodsClass.pageData.pageSize, this.goodsClass.pageData.currentPage)
        this.goodsClass.dialog = true
      }
    },

    // 商品弹窗确认选择
    handleSelectGoods () {
      if (this.goodsClass.isSelect(2, this, '请先选择商品！')) {
        this.goodsClass.multipleSelectTable.forEach(i => {
          i.goodsId = i.id
          i.goodsName = i.name
          i.goodsUnit = i.goodsPackParameterId
          i.goodsSpec = i.parameter
          i.isFreight = 0
        })
        this.goodsClass.multipleSelectTable.forEach(i => {
          delete i.id
        })
        this.tableData = this.goodsClass.handleMultipleConfirm(this.tableData, 'goodsId')
        this.goodsClass.dialog = false
      }
    },

    // 删除一条选择的商品
    _handleDelete (index) {
      this.tableData.splice(index, 1)
    },

    // 返回
    goBack () {
      history.back();
    }
  }
}
</script>
